package com.yunhe.tianhe.rentcars.service.client.Impl;/**
 * Created by Administrator on 2017/11/30 0030.
 */

import com.yunhe.tianhe.commons.dto.Pageable;
import com.yunhe.tianhe.rentcars.dao.client.ClientDao;
import com.yunhe.tianhe.rentcars.dao.client.CreditRecordDao;
import com.yunhe.tianhe.rentcars.entity.client.Client;
import com.yunhe.tianhe.rentcars.entity.client.Credit;
import com.yunhe.tianhe.rentcars.entity.system.MemberLevel;
import com.yunhe.tianhe.rentcars.service.client.CreditRecordService;
import com.yunhe.tianhe.rentcars.service.system.MemberLevelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @user yanxiu
 * @creat 2017-11-30 下午 12:06
 * @desc
 **/

@Service
public class CreditRecordServiceImpl implements CreditRecordService {

    @Autowired
    private CreditRecordDao creditRecordDao;
    @Autowired
    private ClientDao clientDao;
    @Autowired
    private MemberLevelService memberLevelService;

    @Override
    public Pageable<Credit> findPage(Integer offset, Integer limit, String name, String mobile, String idCard) {
        List<Credit> data = creditRecordDao.findPage(offset, limit, name, mobile, idCard);
        Pageable<Credit> pageable = new Pageable<>();
        Long count = creditRecordDao.countLines(name, mobile, idCard);
        pageable.setPage(offset / limit + 1);
        pageable.setSize(limit);
        pageable.setTotal(count);
        pageable.setRows(data);
        return pageable;
    }


    @Override
    public void save(Credit credit,String mobile) {
        creditRecordDao.save(credit);


        String creditChange = credit.getCreditChange();
        String symbol = creditChange.substring(0,1);
        String numberStr = creditChange.substring(1);
        Integer number = Integer.valueOf(numberStr);
        Client client = clientDao.findOneByMobile(mobile);
        Integer creditNum = client.getCreditNum();     //修改信用值
        if(symbol.equals("+")){
            creditNum+=number;
        }else{
            creditNum-=number;
        }
        client.setCreditNum(creditNum);

        List<MemberLevel> memberLevels = memberLevelService.findList();  //修改会员级别
        for(MemberLevel member:memberLevels){
            int minScore = member.getMinScore();
            int maxScore = member.getMaxScore();
            if(maxScore>creditNum && creditNum>=minScore){
                client.setMemLevel(member.getLevelId());
            }
        }

        clientDao.updateByCredit(client);
    }
}
